"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : WDR
Case Name   : 开启数据库监控快照功能，验证快照生成方式（手动+自动）
Create At   : 2023.1.6
Owner       : opentestcase009
Description :
    1、修改参数，开启快照功能
    2、使用默认系统库，查看当前快照数据
    3、手动生成快照，并查看快照
    4、查看wdr_snapshot_interval快照生成间隔时间，并将时间修改为10min
    5、修改系统时间为15min后，查看自动生成快照信息
    6、清理环境，恢复参数
Expect      :
    1、开启快照功能成功
    2、查看快照数据成功
    3、手动生成快照成功，查看成功
    4、修改快照生成时间成功
    5、修改系统时间成功，查看快照生成成功
    6、清理环境成功，恢复参数成功
History     :
"""

import os
import time
import unittest
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class WDR(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.sh_pri = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryRoot')
        self.constant = Constant()
        self.config_wdr = "enable_wdr_snapshot"
        self.config_interval = "wdr_snapshot_interval"
        self.table = 'snapshot.snapshot'

    def test_wdr(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '-----step1:检查参数，修改参数配置;expect:成功-----'
        self.log.info(text)

        check_wdr = self.sh_pri.execut_db_sql(f'''show {self.config_wdr};''')
        if 'on' != check_wdr.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_wdr} = "on"''')

        param = self.sh_pri.execut_db_sql(f'''show {self.config_wdr};''')
        self.assertEqual('on', param.splitlines()[-2].strip(),
                         '执行失败:' + text)

        text = '-----step2:查看快照数据;expect:查看快照数据成功-----'
        self.log.info(text)

        select_cmd = f'''select pg_sleep(15);
            select count(*) from {self.table};'''
        show_res1 = self.sh_pri.execut_db_sql(select_cmd, dbname='postgres')
        self.log.info(show_res1)
        self.assertEqual('1', show_res1.splitlines()[-2].strip(),
                         '执行失败:' + text)

        text = '-----step3:手动生成快照;expect:生成快照成功-----'
        self.log.info(text)

        create_snap = f'''select create_wdr_snapshot();
            select pg_sleep(15); 
            select count(*) from {self.table};'''
        self.log.info(create_snap)
        create_res = self.sh_pri.execut_db_sql(create_snap, dbname='postgres')
        self.log.info(create_res)
        self.assertEqual('2', create_res.splitlines()[-2].strip(),
                         '执行失败:' + text)

        text = '-----step4:修改wdr_snapshot_interval参数为10min;expect:修改成功-----'
        self.log.info(text)

        check_interval = self.sh_pri.execut_db_sql(
            f'''show {self.config_interval}''')
        if '10min' != check_interval.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_interval} = "10"''')

        param = self.sh_pri.execut_db_sql(f'''show {self.config_interval}''')
        self.log.info(param)
        self.assertEqual('10min', param.splitlines()[-2].strip(),
                         '执行失败:' + text)

        text = '-----step5.1:修改系统时间为15min后;expect:修改成功-----'
        self.log.info(text)

        date = 'date "+%T"'
        date_cur = self.user_node.sh(date).result()
        self.log.info(date_cur)

        date_after = f'''date -d "{date_cur} 15minute" "+%T"'''
        date_after_res = self.user_node.sh(date_after).result()
        self.log.info(date_after)
        self.log.info(date_after_res)

        date_sh = f'''date -s {date_after_res}'''
        self.log.info(date_sh)
        date_res = self.user_node.sh(date_sh).result()
        self.log.info(date_res)

        time.sleep(20)

        text = '-----step5.2:再次查看快照数据;expect:产生新的快照数据-----'
        self.log.info(text)

        show_res2 = self.sh_pri.execut_db_sql(select_cmd, dbname='postgres')
        self.log.info(show_res2)
        self.assertEqual('3', show_res2.splitlines()[-2].strip(),
                         '执行失败:' + text)

    def tearDown(self):
        text = '-----step6:清理环境,还原参数;expect:成功-----'
        self.log.info(text)

        drop_snapshot = f'''truncate table {self.table};
            select count(*) from {self.table};'''
        self.log.info(drop_snapshot)
        drop_res = self.sh_pri.execut_db_sql(drop_snapshot, dbname='postgres')
        self.log.info(drop_res)

        recov_wdr = self.sh_pri.execut_db_sql(f'''show {self.config_wdr};''')
        if 'off' != recov_wdr.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_wdr} = "off"''')

        param1 = self.sh_pri.execut_db_sql(f'''show {self.config_wdr};''')
        self.log.info(param1)

        recov_interval = self.sh_pri.execut_db_sql(
            f'''show {self.config_interval}''')
        if '1h' != recov_interval.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_interval} = "60"''')

        param2 = self.sh_pri.execut_db_sql(f'''show {self.config_interval}''')
        self.log.info(param2)

        recov_time = time.strftime('%H:%M:%S', time.localtime(time.time()))
        self.log.info(recov_time)
        set_time = self.user_node.sh(f'''date -s {recov_time}''').result()
        self.log.info(set_time)
        current_time = self.user_node.sh('date "+%T"').result()
        self.log.info(current_time)

        self.assertEqual('1h', param2.splitlines()[-2].strip(), '参数恢复成功')
        self.assertEqual('off', param1.splitlines()[-2].strip(), '参数恢复成功')
        self.assertEqual('0', drop_res.splitlines()[-2].strip(),
                         '执行失败:' + text)
        self.log.info(f'----{os.path.basename(__file__)} end-----')
